package com.fwh.gmall.dao;

import com.fwh.gmall.dto.ElectricData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * 家庭组电量数据访问层
 */
@Repository
public class ElectricDao {
    @Autowired
    @Qualifier("getStarRocksJdbcTemplate")
    private JdbcTemplate getStarRocksJdbcTemplate;

    /**
     * 根据参数查询电量统计数据
     * @param type (1:日, 2:周, 3:月, 4:年, 5:全部)
     * @param startDate 开始日期
     * @param homeGroupId 家庭组ID
     * @return 电量统计数据列表
     */
    public List<ElectricData> queryElectricData(Integer type, String startDate, Integer homeGroupId) throws IllegalAccessException {
        String sql = buildQuerySql(type, startDate, homeGroupId);
        return getStarRocksJdbcTemplate.query(sql, new BeanPropertyRowMapper<>(ElectricData.class));
    }

    /**
     * 构建查询SQL
     */
    private String buildQuerySql(Integer type, String startDate, Integer homeGroupId) throws IllegalAccessException {
        StringBuilder sql = new StringBuilder();

        switch (type) {
            case 1:
                sql.append("select * from gmall_electric  ");
                sql.append("where home_group_id = ? ");
                sql.append(homeGroupId);
                sql.append("and daytime >= '").append(startDate).append("' ");
                break;
            case 2:
                sql.append("select * from gmall_electric where 1=1 ");
                sql.append("and daytime <= '").append(startDate).append("' ");
                break;
            case 3:
                  sql.append("select * from gmall_electric where 1=1 ");
                  sql.append("and daytime >= '").append(startDate).append("' ");
                  sql.append("and daytime <= '").append(startDate).append("' ");
                  break;
            case 4:
                sql.append("select * from gmall_electric where 1=1 ");
                sql.append("and daytime >= '").append(startDate).append("' ");
                sql.append("and daytime <= '").append(startDate).append("' ");
                break;
            case 5:
                sql.append("select * from gmall_electric where 1=1 ");
                sql.append("and daytime >= '").append(startDate).append("' ");
                sql.append("and daytime <= '").append(startDate).append("' ");
                break;
            default:
                throw new IllegalAccessException("不支持的查询类型: " + type);
        }
        return sql.toString();

    }


}
